package com.yuji.aacar.widgets.bigpic;

import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
import android.widget.ScrollView;

import com.yuji.aacar.R;


/**
 *<li>Package: {@link MaxScrollView}
 *<li>Date: 2017/6/21 17:55
 *<li>Discription: 支持maxHeight属性的ScrollView
 */

public class MaxScrollView extends ScrollView {
    private int maxHeight;//最大高度

    public MaxScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    public MaxScrollView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(attrs);
    }

    private void init(AttributeSet attrs) {
        TypedArray array = getContext().obtainStyledAttributes(attrs, R.styleable.MaxScrollView);
        if (array != null) {
            maxHeight = (int) array.getDimension(R.styleable.MaxScrollView_msv_maxHeight, 500);
            array.recycle();
        }
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int childCount = getChildCount();
        int height = 0;
        if (childCount == 1) {
            //获得child高度
            height = getChildAt(0).getMeasuredHeight();
            //当前高度大于最大高度，则使用最大高度
            if (height > maxHeight && maxHeight > 0) {
                height = maxHeight;
            }
        }
        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), height);
    }
}
